<?php
//include 'function.php';
class AdminController extends Zend_Controller_Action
{
  private $db;
  public function init()
  {
    $db_obj = new myDb();
    $this->db = $db_obj->getDb();

    Zend_Db_Table::setDefaultAdapter($this->db);
    $this->cat_tags_table = new Application_Model_DbTable_Cattags();
    $this->category_table = new Application_Model_DbTable_Category();
    $this->cont_table = new Application_Model_DbTable_Content();

    $action = $this->getRequest()->getParam("action");
    if ($action === "update-head-cat" ||
	$action === "update-search-cat" ||
	$action === "update-home" ||
	$action === "transaction-handler")
      return;


    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (!isset($session->user))
      {
	/* print "session user not set.===========<br/>"; */
	header("Location: /account/login");
      }
    else if ($session->user->get("type") != Application_Model_User::$ROLE_ADMIN)
      {
	/* print "not ADMIN ROLE ============<br/>"; */
	$res = false;
	$msg = "你没有管理权限。";
	header("Location: /user/msg?res=$res&msg=".urlencode($msg));
      }
    try{
      if (!is_file(LOG))
	  touch(LOG);
      $writer = new Zend_Log_Writer_Stream(LOG);
      $this->logger = new Zend_Log($writer);  
      $this->logger->info("create log");
    }
    catch(Zend_Log_Execption $e)
    {
	print $e->getMessage();
    }
  }

  public function indexAction()
  {
    header("Location: /admin/category");
  }
  /* do nothing but show the execute result in msg.phtml. */
  public function msgAction()
  {
  }

  public function addCategoryAction()
  {
    /* get parent menus */
    $mapper = new Application_Model_CategoryMapper();
    $this->view->parents = $mapper->getCategoryList(0);
  }
  public function delCategoryAction()
  {
    $mapper = new Application_Model_CategoryMapper();
    if ($mapper->delete($_GET['cat_id']))
      {
	$res = true;
	$msg = "删除成功";
      }
    else
      {
	$res = false;
	$msg = "删除失败";
      }
    header("Location: /admin/msg?res=$res&msg=".urlencode($msg));

  }
  public function editCategoryAction()
  {
    /* get parent menus */
    $mapper = new Application_Model_CategoryMapper();
    $this->view->parents = $mapper->getCategoryList(0);

    $cat = new Application_Model_Category();
    $mapper->find($_GET["cat_id"], $cat);
    $this->view->category = $cat;
  }
  public function insertCategoryAction()
  {
    $cat = new Application_Model_Category($_POST);
    $mapper = new Application_Model_CategoryMapper();
    if ($mapper->save($cat))
      {
	$res = 1;
	$msg = "保存成功";
      }
    else
      {
	$res = 1;
	$msg = "保存失败";
      }
    header("Location: /admin/msg?res=$res&msg=".urlencode($msg));
  }


  public function categoryAction()
  {
    $where = null;
    $mapper = new Application_Model_CategoryMapper();
    $parent = Application_Model_CategoryMapper::getLastCatId($_POST);
    print "parent: $parent;";
    /* die(); */
    $this->view->path = $mapper->categoryPathAction($parent);
    /* $this->setLastCatId($_POST, $cat_id); */
    /* $parent = (isset($_POST["second_parent"]) && $_POST["second_parent"] != 0 ) ? $_POST["second_parent"] : (isset($_POST["parent"]) ? $_POST["parent"] : 0); */


    if (isset($parent))
      {
	$where = "parent = $parent or id = $parent";
      }

    $this->view->select_category = isset($_POST["parent"]) ? $_POST["parent"] : 0;
    $this->view->select_second_category = isset($_POST["second_parent"]) ? $_POST["second_parent"] : 0;

    /* get parent menus */
    $mapper = new Application_Model_CategoryMapper();
    $this->view->parents = $mapper->getCategoryList(0);
    $this->view->second_parents = $mapper->getCategoryList($this->view->select_category);

    $this->view->categories = $mapper->fetchAll($where, "id");
  }

  public function tagsAction()
  {
    $this->view->categories = $this->category_table->fetchAll();
    //$this->view->categories = $result->fetchAll();    
    if ($this->getRequest()->isPost())
      {
	$this->cat_tags_table->insert($this->getRequest()->getPost());
	
	/* get the tags with this category */
	$where = $this->db->quoteInto('cat_id = ?', $this->getRequest()->getParam('cat_id'));
	$this->view->tags = $this->cat_tags_table->fetchAll($where);
      }
    $this->view->cat = $this->getRequest()->getParam('cat_id');
  }

  /* 每天更新一次首页，手动更新，产生index 页面 */
  public function updateHomeAction()
  {
    /***************************************************************************************/
    /* 找出最近一天最热的6个课程 */
    $select = $this->db->select();
    $select->from("view_history", array("view_history.cont_id", "content.title", "content.thumb", "content.path", "content.ori_price", "content.dis_price","content.promotion","content.duration", "sum"=>"count(view_history.view_time)"))
      ->join("content", "content.id = view_history.cont_id")
      ->where("view_history.view_time>date_sub(curdate(), interval 1 day)")
      ->group("view_history.cont_id")
      ->order("sum desc")
      ->limit(6);
    $result = $this->db->fetchAll($select);
    $this->view->top_courses = array();
    $i=1;
    foreach($result as $res)
      {
	if ($i<6)
	  $this->view->top_courses[] = $res;
	else
	  $this->view->today_hot_course = $res;
	$i++;
      }

    /***************************************************************************************/
    // 找出一周内播放排行榜前十名
    $select = $this->db->select();
    $select->from(array("v"=>"view_history"), array("v.cont_id", "c.title", "c.thumb", "c.ori_price", "c.dis_price", "c.promotion", "sum"=>"count(v.cont_id)"))
      ->join(array("c"=>"content"), "v.cont_id=c.id ")
      ->where("v.view_time>date_sub(curdate(), interval 7 day) ")
      ->group("v.cont_id")
      ->order("sum desc")
      ->limit(10);
    $this->view->top_10_courses_in_week = $this->db->fetchAll($select);

    /***************************************************************************************/
    /* 找出被播放课程最多的前十位用户 */
    $select = $this->db->select();
    $select->from(array("v"=>"view_history"), array("u.id", "u.username", "u.email", "play_times"=>"count(*)"))
      ->join(array("c"=>"content"), "v.cont_id=c.id ")
      ->join(array("u"=>"users"), "u.id=c.uid ")
      /* ->where("v.view_time>date_sub(curdate(), interval 7 day)") */
      ->group("c.uid")
      ->limit(10);
    $this->view->top_users = $this->db->fetchAll($select);

    /***************************************************************************************/
    /* 统计每个类播放次数排行 */
    $catmapper = new Application_Model_CategoryMapper();
    $cats_play_info = $catmapper->getCategoryPlayTimes();

    /***************************************************************************************/
    /* 遍历每一个主类别,找出每个类别中最热的三个子类，和这三个子类中最热的四个课程。 */
    $main_cats = $catmapper->getCategoryList(0);
    $this->view->cats = array();
    $j=0;
    foreach($main_cats as $id=>$name)
      {
	if($j++ > MAX_MAIN_CATLOG)
		break;
	/* 获取这个类别中所有等级的子类 */
	$all_sub_cats = $catmapper->getAllSubCategory($id);
	$cat_play_times = array();

	// 计算每个等级的播放次数
	foreach($all_sub_cats as $sub_id=>$cat)
	  {
	    $cat_play_times[$sub_id] = isset($cats_play_info[$cat->get("id")]) ? $cats_play_info[$cat->get("id")] : 0;
	  }
	// 按播放次数排序
	arsort($cat_play_times, SORT_NUMERIC);

	$courses = array();
	$cats = array();
	$i=0;
	if (isset($cat_play_times) && count($cat_play_times) > 0)
	  {
	    // 遍历子类
	    foreach($cat_play_times as $cat_id => $times)
	      {
		// 获取前三个最热的子类
		if ($i++ > 2)
		  break;
		$cat_name = $all_sub_cats[$cat_id]->get("name");
		$cats[] = $cat_name;

		/* 挑出这个子类中最热（收看次数最多）的四个课程 */
		$select = $this->db->select();
		$select->from(array("c"=>"content"), array("c.id", "c.title", "c.thumb", "c.ori_price", "c.dis_price", "c.duration","c.promotion", "times"=>"count(v.id)"))
		  ->join(array("v"=>"view_history"), "c.id = v.cont_id")
		  ->where("c.cat_id=$cat_id")
		  ->group("c.id")
		  ->order("times desc")
		  ->limit(14);

		$courses[$cat_name] = $this->db->fetchAll($select);
	      }
	  }
	$this->view->cats[] = array('name'=>$name, 'id'=>$id, 'cats'=>$cats, 'courses'=>$courses);
      }
  }
  public function updateTagAction()
  {
    $select = $this->db->select();
    $select->from("cat_tags", array("tag", "id"))
      ->distinct(true);
    $tags_table = new Application_Model_DbTable_Tags();
    foreach($this->db->fetchAll($select) as $tag)
      {
	print $tag['tag']."  ";
	$where = $this->db->quoteInto('tag = ?', $tag['tag']);
	$res = $tags_table->update(array("tag_id"=>$tag['id']), $where);
	print "update row $res<br/>";
      }
  }
  public function updateHeadCatAction()
  {
    $mapper = new Application_Model_CategoryMapper();
    $this->view->cats = $mapper->getCategoryList(0);
    /* $cats = $this->category_table->fetchAll(); */
    /* $this->view->cats = $cats; */
  }
  public function updateSearchCatAction()
  {
    $mapper = new Application_Model_CategoryMapper();
    $this->view->cats = $mapper->getCategoryList(0);
  }
  public function createHomeAction()
  {
    // update the index-body
    $home_page = file_get_contents("http://{$_SERVER['HTTP_HOST']}/admin/update-home");
    $fp = fopen(APPLICATION_PATH.'/views/scripts/index/index-body.phtml', "w");
    $this->view->create_home = fwrite($fp, $home_page);
    fclose($fp);

    // update the head category
    $head_page = file_get_contents("http://{$_SERVER['HTTP_HOST']}/admin/update-head-cat");
    $fp = fopen(APPLICATION_PATH.'/views/scripts/index/category-body.phtml', "w");
    $this->view->create_head = fwrite($fp, $head_page);
    fclose($fp);

    // update the search category
    $cat = file_get_contents("http://{$_SERVER['HTTP_HOST']}/admin/update-search-cat");
    $fp = fopen(APPLICATION_PATH.'/views/scripts/index/search-cat.phtml', "w");
    $this->view->cat_page = fwrite($fp, $cat);
    fclose($fp);

  }
  /* set status to 2 in pay history item ; 
   * param 
   * @ id primary key of pay history table
   */
  public function refundAction()
  {
    $pay = new Application_Model_PayHistory();
    $mapper = new Application_Model_PayHistoryMapper();
    $mapper->find($_GET["pay_id"], $pay);

    /* Zend_Session::start(); */
    /* $session = new Zend_Session_Namespace('account'); */
    /* if ($pay->get("buyer_id") != $session->user->get("id")) */
    /*   { */
    /* 	$this->view->res = false; */
    /* 	$this->view->msg = "你无权进行此操作。"; */
    /*   } */
    /* else  */
    if ($pay->get("status") == Application_Model_PayHistory::$TRANSCATION_REFUNDED)
      {
	$res = false;
	$msg = "此课程已经退款，请勿重复提交。";
      }
    else if ($pay->get("status") == Application_Model_PayHistory::$TRANSCATION_DONE)
      {
	$res = false;
	$msg = "订购已完成，请在购买24小时内退款。";
      }
    else if ($pay->get("status") == Application_Model_PayHistory::$TRANSCATION_REFUND_REQUEST)
      {
	/* do the refund */
	$pay->set("status", Application_Model_PayHistory::$TRANSCATION_REFUNDED);
	$mapper->save($pay);

	/* refund the money to buyer's account */
	$user = new Application_Model_User();
	$usermapper = new Application_Model_UserMapper();
	$usermapper->find($pay->get("buyer_id"), $user);

	$user->set("wealth", $user->get("wealth") + $pay->get('price'));
	$usermapper->save($user);

	$res = true;
	$msg = "退款已完成，款项已退回买家账户。";
      }
    header("Location: /admin/msg?res=$res&msg=".urlencode($msg));
  }
  public function refundListAction()
  {
    /* $pay = new Application_Model_PayHistory(); */
    /* $mapper = new Application_Model_PayHistoryMapper(); */
    /* $this->view->refund_request =  */
    /*   $mapper->fetchAll("status = ".Application_Model_PayHistory::$TRANSCATION_REFUND_REQUEST); */


    $select = $this->db->select();
    $select->from(array("p"=>"pay_history"), 
		  array("pay_id"=>"p.id", "c.title", "c.descript", "u.username", "u.email", "p.status", "p.price", "p.time"))
      ->join(array("u"=>"users"), "u.id = p.buyer_id")
      ->join(array("c"=>"content"), "c.id = p.cont_id")
      ->where("p.status = ".Application_Model_PayHistory::$TRANSCATION_REFUND_REQUEST)
      ->order("p.id desc");
    /* print $select; */
    $results = $this->db->fetchAll($select);
    /* print_r($this->view->results); */
    /* die(); */

    /* set pageinator */
    $page = 1;
    if(isset($_GET['page']) && is_numeric($_GET['page'])){
      $page = $_GET['page'];
    }
    $paginator = Zend_Paginator::factory($results);
    $paginator->setCurrentPageNumber($page)->setItemCountPerPage(NUM_PER_PAGE);
    $this->view->orders = $paginator;    

  }

  /* 扫描pay_history表， 对每一个大于24小时的交易，将状态设置DONE，同时给卖家打款。*/
  public function transactionHandlerAction()
  {
    $msg = "";
    $mapper = new Application_Model_PayHistoryMapper();
    $pays = $mapper->fetchAll("status = ".Application_Model_PayHistory::$TRANSCATION_DOING." and time < date_sub(now(), interval 1 day)");
    if (!isset($pay) || (count($pays) < 1))
      {
	$this->view->msg = "最近24小时内没有购买记录。";
	return;
      }

    $usermapper = new Application_Model_UserMapper();
    $admin = new Application_Model_User();
    $usermapper->findObj("type = ".Application_Model_User::$ROLE_ADMIN, $admin);    

    /* cycle the pay trancations */
    foreach ($pays as $pay)
      {
	/* change the status to DONE */
	$pay->set("status", Application_Model_PayHistory::$TRANSCATION_DONE);
	if ($mapper->save($pay))
	  {
	    $msg .= "order id ".$pay->get('id').", ".$pay->get('price')."￥ set to TRANSCATION_DONE success; ";
	    /* give the 70% money to seller */
	    $user = new Application_Model_User();
	    $usermapper->find($pay->get("owner_id"), $user);
	    $user->set("wealth", $user->get("wealth") + $pay->get('price') * 0.7);

	    if ($usermapper->save($user))
	      {
		$msg .= $user->get("username") ? $user->get("username") : $user->get("email")."+ ".$pay->get('price') * 0.7."￥ success; ";
	      }
	    else
	      {
		$msg .= $user->get("username") ? $user->get("username") : $user->get("email")."+ ".$pay->get('price') * 0.7."￥ failed; ";
	      }

	    /* give the 30% money to admin */
	    $admin->set("wealth", $admin->get("wealth") + $pay->get('price') * 0.3);
	    if ($usermapper->save($admin))
	      {
		$msg .= $admin->get("username") ? $admin->get("username") : $admin->get("email")."+ ".$pay->get('price') * 0.3."￥ success";
	      }
	    else
	      {
		$msg .= $admin->get("username") ? $admin->get("username") : $admin->get("email")."+ ".$pay->get('price') * 0.3."￥ failed";
	      }

	  }
	else
	    $msg .= $pay->get('id')." ".$pay->get('price')." to TRANSCATION_DONE failed; ";
	$msg .= " \n<br/>";
      }
    $this->view->msg = $msg;

    /* update admin session */
    Zend_Session::start();
    $session = new Zend_Session_Namespace('account');
    if (isset($session->user) && $session->user->get("id"))
      {
	$usermapper = new Application_Model_UserMapper();
	$usermapper->find($session->user->get("id"), $session->user);
      }
  }
  function getExtend($file_name)
  {
    $extend =explode("." , $file_name);
    return end($extend);
  }
  /*
   * get base filename with out extend
   **/
  function getFileName($file_name)
  {
    $arr =explode("." , $file_name);
    unset($arr[count($arr)-1]);
    return implode(".", $arr);
  }
  public function converttoflv( $in, $out )
  {

    /* $cmd = "/usr/local/bin/ffmpeg -v 0 -i $in -ar 11025 $out 2>&1"; */
    $cmd = FFMPEG." -v 0 -i $in -ar 11025 $out 2>&1";
    $fh = popen( $cmd, "r" );
    $this->logger->info("-----------------------------");
    while($c = fgets( $fh ) ) 
      {
	$this->logger->info($c);
      }
    pclose( $fh );
    $this->logger->info("-----------------------------");
  }
  public function getthumbnail( $in, $out )
  {
    //unlink( $out );
    // $cmd = "ffmpeg.exe -i $in -pix_fmt rgb24 -vframes 1 -s 300x200 $out 2>&1";
    $cmd = FFMPEG." -i {$in} -an -ss 00:00:03 -an -r 1 -vframes 1 -y {$out} 2>&1";
    /* $cmd = "/usr/local/bin/ffmpeg -i $in -pix_fmt rgb24 -vframes 1 -s 300x200 $out 2>&1"; */
    // print 'cmd: '.$cmd.'<br/>';
    $this->logger->info("$cmd");
    $fh = popen( $cmd, "r" );
    //while( fgets( $fh ) ) { }
    //$this->logger->info("-----------------------------");
    while($c = fgets( $fh ) ) 
      {
	//$this->logger->info($c);
      }
    //$this->logger->info("-----------------------------");
    pclose( $fh );
  }
  /*
   * import a directory videos into content table
   * $_GET["cat_id"]  specify the category id
   **/
  public function importDirVideoToDbAction()
  {
	  $vod_dir = SITE_ROOT."/import/";
	  if (!is_dir($vod_dir))
	  {
		  die("$vod_dir is not a directory");
	  }
	  if (!$dh = opendir($vod_dir))
	  {
		  die("open $vod_dir failed");
	  }
	  while (($file_name = readdir($dh)) !== false)
	  {
		  $this->logger->info("===============================");
		  if ($file_name == "." || $file_name == "..")
		  {
			  $this->logger->info("$file_name continue");
			  continue;
		  }
		  $title = $this->getFileName($file_name);
		  print "handling $file_name , ";
		  print "title: $title<br/>";
		  //continue;
		  $this->logger->info("handling : ".$file_name);
		  $this->logger->info("get title: ".$title);
		  $size = 0;
		  $format = $this->getExtend($file_name);
		  $md5 = md5($file_name.date("Y-m-d H:i:s"));
		  $this->logger->info("get filename: ".$file_name);
		  $this->logger->info("get format: ".$format);
		  $this->logger->info("get md5: ".$md5);

		  /* rename the original filename to md5 filename */
		  $file = $md5.".".$format;
		  $r = rename($vod_dir.$file_name, VIDEO_PATH.$file);
		  $this->logger->info("rename :" .$vod_dir.$file_name ." to ". VIDEO_PATH.$file);
		  $this->logger->info("result: ".$r);

		  /* convert to flv */
		  if (strpos(FORMAT_NEED_CONVERT, $format))
		  {
			  $file1 = $md5.".flv";
			  $this->logger->info("need to convert");
			  $this->logger->info("convert ".VIDEO_PATH.$file . " to " . VIDEO_PATH.$file1);
			  $this->converttoflv(VIDEO_PATH.$file, VIDEO_PATH.$file1);
			  $file = $file1;
		  }
		  /* get thumbnail */
		  $thumbnail = $md5.'.jpg';
		  $this->getthumbnail(VIDEO_PATH.$file,
				  THUMBNAILS_PATH.$thumbnail);
		  $this->logger->info("get thumbnail ".THUMBNAILS_PATH.$thumbnail);
		  $duration = Application_Model_ContentMapper::video_duration(VIDEO_PATH.$file);

		  /* insert to content table*/
		  $param = array(//'id' => '1',
				  'title'=>$title,
				  'descript'=>$title,
				  'cat_id'=>$_GET["cat_id"],
				  'path'=>$file,
				  'format'=>$format,
				  'size'=>$size,
				  'uid'=>$_GET["uid"],
				  'ori_price'=>0,
				  'dis_price'=>0,
				  'promotion'=>0,
				  'thumb'=>$thumbnail,
				  //$duration = Application_Model_ContentMapper::video_duration(VIDEO_PATH.$file));
				  'duration'=>$duration['duration'],
				  'seconds'=>$duration['seconds'],
				);
		  $content = new Application_Model_Content($param);
		  $cont_mapper = new Application_Model_ContentMapper();
		  $cont_id = $cont_mapper->save($content);
		  $this->logger->info("save content");

		  /* insert 10 times to view history */
		  $history = new Application_Model_DbTable_History();
		  Zend_Session::start();
		  $session = new Zend_Session_Namespace('account');
		  $history->insert(array('uid'=>$session->user->get("id"), 'cont_id'=>$cont_id));
		  $this->logger->info("insert into view history");
	  }	
	  closedir($dh);
  }
  function send_mail($from, $to, $subject, $message)  
  {  
	  if ($from == "")  
	  {  
		  $from = '乐课网 <leke100.net@sohu.com>';//发件人地址  
	  }  
	  $headers = 'MIME-Version: 1.0' . "\r\n";  
	  $headers .= 'Content-type: text/html; charset=utf8' . "\r\n";  
	  $headers .= 'From: ' . $from . "\r\n";  
	  return mail($to, $subject, $message, $headers);  
  }
  public function sendNotificationAction()
  {
	  $mapper = new Application_Model_TeachersMapper();
	  $teachers = $mapper->fetchAll("email is not null");

	  $from = "=?GB2312?B?wNa/zs34?=<leke100.net@sohu.com>";
	  $subject = "=?GB2312?B?wNa/zs340fvE+rS0sOzX1Ly6tcTN+MnPxeDRtbDg?=";
	  //$message    =   '<html>尊敬的 [Sir]:<br/><br/><a href="http://www.leke100.net"><img src="http://leke100.net/iask/mail.pic.jpg"/></a></html>';
	  $message    =   '<html><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><div style="text-align: left"><pre>尊敬的 [Sir]:<br/>
我爱进步网 改名为 "乐课网"。

乐课网是一个综合的视频学习平台，您可以在此免费开办自己的培训班，自主定价！

每当您的付费课程被收看一次，您就可以从中获取一次收益。一次投入，
永远收益(网站只从您已出售的课程中提取30%管理费用，除此不再收任何其他费用)

步骤：
1、打开乐课网， http://www.leke100.net ,注册(改版后注册过的无需重复注册);
联通用户，请使用专用线路： http://www.leke100.org

2、登录，上传课程，设置课程的价格。

3、每当用户观看您的付费课程，就会从他/她的账户中扣除相应的费用（用户通过支付宝向自己的账户充值），
24小时内，用户可以退课；24小时后，这笔费用的70%将会划入您的账户。

4、您随时可以跟客服联系，将账户内的金额兑换到您的支付宝账号。

欢迎各位老师，入驻乐课网，抢占先机，推广火热进行中。


乐课网
leke100.net@sohu.com
2011/11/12
</pre>
</div>
</html>';

	  $count = 0;
	  foreach($teachers as $teacher)
	  {
		  //print $teacher->get("name").": ".$teacher->get("email")."<br/>";
		  echo $count++."  send mail to name: ".$teacher->get("name").", email: ".$teacher->get("email")."<br/>";
		  $body = str_replace("[Sir]", $teacher->get("name"), $message);
		  //$this->send_mail($from, "xiaopei0206@gmail.com", $subject, $body);  
		  $this->send_mail($from, $teacher->get("email"), $subject, $body);  

		  /*
		  // only for test
		  if ($count > 4)
		  break;
		   */
	  }
  }

  // 通知邮件订阅者， 视频课程更新列表
  public function addSubscribeAction()
  {
    $subscribe = new Application_Model_Subscribe();
    $mapper = new Application_Model_SubscribeMapper();

    $catmapper = new Application_Model_CategoryMapper();

    $this->view->cats = $catmapper->getCategoryTree(0);
    print "<pre>";
    print_r($this->view->cats);
    print "</pre>";
    // foreach($root_cats as $id=>$name)
    //   {
    // 	print $name;
    // 	print "<br/>";

    // 	$all_sub_cats = $catmapper->getCategoryList($id);
    // 	foreach($all_sub_cats as $sub_cat)
    // 	  {
    // 	    print "&nbsp;&nbsp;&nbsp;&nbsp;".$sub_cat->get("name");
    // 	    print "<br/>";
    // 	  }
    //   }
  }

  // 通知邮件订阅者， 视频课程更新列表
  public function sendUpdateToSubscribeAction()
  {
    $mapper = new Application_Model_SubscribeMapper();
    $this->view->subscribes = $mapper->fetchAll("email is not null");
  }

  public function setDurationOfContentAction()
  {
	  $cont_mapper = new Application_Model_ContentMapper();
	  $conts = $cont_mapper->fetchAll("id<20");
	  //$conts = $cont_mapper->fetchAll("duration is null");

	  foreach($conts as $cont)
	  {
		  print "process ";
		  print $cont->get("id")." ";
		  print $cont->get("path");
		  $info = Application_Model_ContentMapper::video_duration(VIDEO_PATH.$cont->get("path"));
		  //$cont->set("duration", $info["duration"]);
		  //$cont->set("seconds", $info["seconds"]);
		  print " duration: ";
		  print_r($info);
		  print $cont->get("title");
		  //$cont_mapper->save($cont);
		  print "<br/>";
	  }

	  /*
	  //================================================
	  // 去掉小数部分
	  $cont_mapper = new Application_Model_ContentMapper();
	  $conts = $cont_mapper->fetchAll();

	  foreach($conts as $cont)
	  {
	  print "process ";
	  print $cont->get("id")." ";
	  print $cont->get("path");
	  print " duration: ";
	  $duration = explode(".", $cont->get("duration"));
	  $cont->set("duration", $duration[0]);
	  print $duration[0];
	  print $cont->get("title");
	  $cont_mapper->save($cont);
	  print "<br/>";
	  }
	   */
  }

}
